﻿using System;
using System.Linq;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using Newtonsoft.Json;
using SnakeGame.Models;
using SnakeGame.Views;

namespace SnakeGame.Helpers
{
    class ConfigManager
    {
        public ConfigManager()
        {
        }

        public static List<Block> ReadConfigFromFile()
        {
            List<Block> myList = new List<Block>();
            try
            {
                string exePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
                exePath += "\\config.json";

                using (FileStream fs = File.Open(exePath, FileMode.Open))
                using (StreamReader sw = new StreamReader(fs))
                {
                    string jsonText = sw.ReadToEnd();
                    myList = (List<Block>)JsonConvert.DeserializeObject(jsonText, typeof(List<Block>));
                    return myList;
                }
            }
            catch
            {
                MessageBox.Show("Unable to read config file (config.json)");
            }
            return myList;
        }

        public static void WriteConfigToFile(List<Block> q, string fileName)
        {
            if (q == null || q.Count == 0)
            {
                return;
            }

            try
            {
                var myQuestions = new List<Block>();
                foreach (var i in q)
                {
                    Block a = new Block
                    {
                        ID = i.ID,
                        IsUsed = i.IsUsed,
                        Win = i.Win,
                        Lose = i.Lose,
                        Timeout = i.Timeout,
                        Ladder = i.Ladder,
                        QuestionList = i.QuestionList
                    };
                    myQuestions.Add(a);
                }

                string json = JsonConvert.SerializeObject(myQuestions, Formatting.Indented);

                if (!File.Exists(fileName))
                {
                    File.Create(fileName);
                }
                File.WriteAllText(fileName, json);
            }
            catch
            {
                MessageBox.Show("Unable to write config file: " + fileName);
            }
        }
    }
}
